<!--
  * 库存信息表（单租户版）
  *
  * @Author:    ADog
  * @Date:      2025-09-20 15:55:03
  * @Copyright  1.0
-->
<template>
    <!---------- 查询表单form begin ----------->
    <a-form class="smart-query-form">
        <a-row class="smart-query-form-row">
            <a-form-item label="关键字查询" class="smart-query-form-item">
                <a-input style="width: 200px" v-model:value="queryForm.keywords" placeholder="关键字查询" />
            </a-form-item>
            <a-form-item label="库存数量" class="smart-query-form-item">
                <a-input style="width: 200px" v-model:value="queryForm.stockQuantity" placeholder="库存数量" />
            </a-form-item>
            <a-form-item class="smart-query-form-item">
                <a-button type="primary" @click="onSearch">
                    <template #icon>
                        <SearchOutlined />
                    </template>
                    查询
                </a-button>
                <a-button @click="resetQuery" class="smart-margin-left10">
                    <template #icon>
                        <ReloadOutlined />
                    </template>
                    重置
                </a-button>
            </a-form-item>
        </a-row>
    </a-form>
    <!---------- 查询表单form end ----------->

    <a-card size="small" :bordered="false" :hoverable="true">
      <div class="rule-content">
      <div class="left-box">
        <!---------- 表格操作行 begin ----------->
        <a-row class="smart-table-btn-block">
            <div class="smart-table-operate-block">
                <a-button @click="showForm" type="primary" size="small">
                    <template #icon>
                        <PlusOutlined />
                    </template>
                    新建
                </a-button>
                <a-button @click="confirmBatchDelete" type="primary" danger size="small" :disabled="selectedRowKeyList.length == 0">
                    <template #icon>
                        <DeleteOutlined />
                    </template>
                    批量删除
                </a-button>
            </div>
            <div class="smart-table-setting-block">
                <TableOperator v-model="columns" :tableId="null" :refresh="queryData" />
            </div>
        </a-row>
        <!---------- 表格操作行 end ----------->

        <!---------- 表格 begin ----------->
        <a-table
            size="small"
            :scroll="{ y: 800 }"
            :dataSource="tableData"
            :columns="columns"
            rowKey="stockId"
            bordered
            :loading="tableLoading"
            :pagination="false"
            :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
        >
            <template #bodyCell="{  record, column }">


                <template v-if="column.dataIndex === 'action'">
                    <div class="smart-table-operate">
                        <a-button @click="showForm(record)" type="link">编辑</a-button>
                        <a-button @click="onDelete(record)" danger type="link">删除</a-button>
                    </div>
                </template>
            </template>
        </a-table>
        <!---------- 表格 end ----------->

        <div class="smart-query-table-page">
            <a-pagination
                showSizeChanger
                showQuickJumper
                show-less-items
                :pageSizeOptions="PAGE_SIZE_OPTIONS"
                :defaultPageSize="queryForm.pageSize"
                v-model:current="queryForm.pageNum"
                v-model:pageSize="queryForm.pageSize"
                :total="total"
                @change="queryData"
                @showSizeChange="queryData"
                :show-total="(total) => `共${total}条`"
            />
        </div>
      </div>
        <div class="right-box">
          <div class="right-box">
            <a-card> <!-- 去掉多余的<template>标签，它不影响渲染但没必要 -->
              <div class="warn-message-container">
                <div class="warn-title">预警信息（共 {{ warnMessageList.length }} 条）</div>
                <!-- 用v-for逐条渲染，每条消息占一行 -->
                <div class="warn-message-item" v-for="(msg, index) in warnMessageList" :key="index">
                  {{ msg }}
                </div>
                <!-- 空消息时显示提示 -->
                <div class="warn-empty" v-if="warnMessageList.length === 0">
                  暂无预警消息
                </div>
              </div>
            </a-card>
          </div>
        </div>
        <StockForm  ref="formRef" @reloadList="queryData"/>
      </div>
    </a-card>
</template>
<script setup>
import { reactive, ref, onMounted, nextTick } from 'vue';
    import { message, Modal } from 'ant-design-vue';
    import { SmartLoading } from '/@/components/framework/smart-loading';
    import { stockApi } from '/@/api/business/wms/stock/stock-api';
    import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
    import { smartSentry } from '/@/lib/smart-sentry';
    import TableOperator from '/@/components/support/table-operator/index.vue';
    import StockForm from './conponents/stock-form.vue';

    // ---------------------------- 表格列 ----------------------------

    const columns = ref([
        {
            title: '库存编码',
            dataIndex: 'stockCode',
            ellipsis: true,
        },
        {
            title: '批次编码',
            dataIndex: 'batchCode',
            ellipsis: true,
        },
        {
            title: '实际库存数量',
            dataIndex: 'stockQuantity',
            ellipsis: true,
        },
        {
            title: '锁定库存数量',
            dataIndex: 'lockedQuantity',
            ellipsis: true,
        },
        {
            title: '生产日期',
            dataIndex: 'productionTime',
            ellipsis: true,
        },
        {
            title: '过期日期',
            dataIndex: 'expirationTime',
            ellipsis: true,
        },

        {
            title: '创建时间',
            dataIndex: 'createTime',
            ellipsis: true,
        },
        {
            title: '备注',
            dataIndex: 'remark',
            ellipsis: true,
        },
        {
            title: '操作',
            dataIndex: 'action',
            fixed: 'right',
            width: 90,
        },
    ]);

    // ---------------------------- 查询数据表单和方法 ----------------------------

    const queryFormState = {
        keywords: undefined, //关键字查询
        stockQuantity: undefined, //库存数量
        pageNum: 1,
        pageSize: 10,
    };
    // 查询表单form
    const queryForm = reactive({ ...queryFormState });
    // 表格加载loading
    const tableLoading = ref(false);
    // 表格数据
    const tableData = ref([]);
    // 总数
    const total = ref(0);

    // 重置查询条件
    function resetQuery() {
        let pageSize = queryForm.pageSize;
        Object.assign(queryForm, queryFormState);
        queryForm.pageSize = pageSize;
        queryData();
    }

    // 搜索
    function onSearch(){
      queryForm.pageNum = 1;
      queryData();
    }

    // 查询数据
    async function queryData() {
        tableLoading.value = true;
        try {
            let queryResult = await stockApi.queryPage(queryForm);
            tableData.value = queryResult.data.list;
            total.value = queryResult.data.total;
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            tableLoading.value = false;
        }
    }


    onMounted(queryData);

    // ---------------------------- 添加/修改 ----------------------------
    const formRef = ref();

    function showForm(data) {
        formRef.value.show(data);
    }

    // ---------------------------- 单个删除 ----------------------------
    //确认删除
    function onDelete(data){
        Modal.confirm({
            title: '提示',
            content: '确定要删除选吗?',
            okText: '删除',
            okType: 'danger',
            onOk() {
                requestDelete(data);
            },
            cancelText: '取消',
            onCancel() {},
        });
    }

    //请求删除
    async function requestDelete(data){
        SmartLoading.show();
        try {
            let deleteForm = {
                goodsIdList: selectedRowKeyList.value,
            };
            await stockApi.delete(data.stockId);
            message.success('删除成功');
            queryData();
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            SmartLoading.hide();
        }
    }

    // ---------------------------- 批量删除 ----------------------------

    // 选择表格行
    const selectedRowKeyList = ref([]);

    function onSelectChange(selectedRowKeys) {
        selectedRowKeyList.value = selectedRowKeys;
    }

    // 批量删除
    function confirmBatchDelete() {
        Modal.confirm({
            title: '提示',
            content: '确定要批量删除这些数据吗?',
            okText: '删除',
            okType: 'danger',
            onOk() {
                requestBatchDelete();
            },
            cancelText: '取消',
            onCancel() {},
        });
    }

    //请求批量删除
    async function requestBatchDelete() {
        try {
            SmartLoading.show();
            await stockApi.batchDelete(selectedRowKeyList.value);
            message.success('删除成功');
            queryData();
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            SmartLoading.hide();
        }
    }

    // WebSocket连接URL
    const wsUrl = 'ws://localhost:1024/ws/message';

    // 创建WebSocket实例
    const websocket = new WebSocket(wsUrl);

    // 连接成功事件
    websocket.onopen = function (event) {
      console.log('WebSocket连接已建立');
      // 可以在这里发送初始消息
      // websocket.send('Hello Server');
    };

    const warnMessageList = ref([]);
    // 接收消息事件
    websocket.onmessage = function (event) {
      let rawMsg = event.data; // 后端发送的原始消息："[物料1..., 物料2..., 物料3...]"
      console.log('收到原始预警消息:', rawMsg);

      // 1. 处理伪数组：去掉前后的[]，得到纯文本（如"物料1..., 物料2..., 物料3..."）
      if (rawMsg.startsWith('[') && rawMsg.endsWith(']')) {
        rawMsg = rawMsg.slice(1, -1).trim(); // slice(1,-1)去掉首尾字符，trim()去除空格
      }

      // 2. 按“逗号+空格”分割成单个消息的数组（适配后端的分隔格式）
      const msgArray = rawMsg ? rawMsg.split(', ') : []; // 空消息时返回空数组

      // 3. 遍历数组，去重后添加到列表（用nextTick确保响应式更新）
      nextTick(() => {
        msgArray.forEach((newMsg) => {
          // 过滤空消息，且避免重复添加
          if (newMsg && newMsg.trim() && !warnMessageList.value.includes(newMsg)) {
            warnMessageList.value.push(newMsg);
          }
        });
      });

      console.log('解析后的预警消息数组:', msgArray);
    };
    // 连接关闭事件
    websocket.onclose = function (event) {
      console.log('WebSocket连接已关闭');
    };

    // 连接错误事件
    websocket.onerror = function (event) {
      console.error('WebSocket连接发生错误:', event);
    };
</script>
<style  scoped>
  .rule-content {
    display: flex;
    justify-content: space-around;
  }

  .left-box {
    flex: 2.5;
  }

  .right-box {
    flex: 1.5;
  }
</style>